import { ref, reactive } from 'vue'
import { userApi } from '@/api/modules/system/user'
import type { User } from '@/api/modules/system/user'

export function useUser(api?: (page: AxiosType.Pagination) => Promise<AxiosType.Response>) {
  const filters = {
    userStatus: [
      { text: '启用', value: '1' },
      { text: '禁用', value: '0' }
    ],
    gender: [
      { text: '男', value: '1' },
      { text: '女', value: '0' }
    ]
  }

  const formatUserStatus = (val: number) => {
    if (val === 1) {
      return '启用'
    } else {
      return '禁用'
    }
  }

  const formatGender = (val: string) => {
    if (val == '1') {
      return '男'
    } else if (val == '0') {
      return '女'
    } else {
      return ''
    }
  }
  const handleFormatter = (row: any, column: any, cellValue: any) => {
    if (column.property === 'gender') {
      return formatGender(cellValue)
    }
  }

  const columns: any[] = [
    { prop: 'userName', label: '姓名', width: 120, fixed: true, isGbk: true },
    { prop: 'userCode', label: '编号', width: 120 },
    { prop: 'loginName', label: '账号', width: 120 },
    {
      prop: 'userStatus',
      label: '状态',
      width: 120,
      filters: filters.userStatus,
      exportFn: (data: any) => formatUserStatus(data)
    },
    { prop: 'positionName', label: '职位', width: 130 },
    { prop: 'cellphone', label: '手机号码', width: 130 },
    { prop: 'email', label: '邮箱地址', width: 180 },
    { prop: 'expiryDate', label: '有效期', width: 150 },
    { prop: 'gender', label: '性别', width: 100, formatter: handleFormatter, filters: filters.gender }
  ]

  const statusData = reactive({} as { [key: string]: number })
  const refTable = ref()
  const tableData = reactive({ resp: { list: [], total: 0 }, loading: false })
  const handleQuery = (page: AxiosType.Pagination) => {
    tableData.loading = true
    if (api) {
      callback(api(page))
    } else {
      callback(userApi.findListPage(page))
    }
  }

  const callback = (promise: Promise<AxiosType.Response>) => {
    promise.then(resp => {
      if (resp.success) {
        tableData.resp = resp.data
        resp.data.list.forEach((u: User) => {
          statusData[u.userId] = u.userStatus
        })
      }
      tableData.loading = false
    })
  }

  return { refTable, tableData, statusData, handleQuery, handleFormatter, filters, formatUserStatus, columns }
}
